<script setup>
import axios from 'axios'
import { onMounted,  ref} from 'vue'
import moment from "moment";



const dataList = ref([]);
let currentPage = ref(1);
let pageSize = ref(5);
let totalCount = ref(0);

const selectedModelType = ref('ALL');  // 默认选择 'ALL'
const modelTypes = ref([{ key: 'all', value: 'ALL' }]);


onMounted(() => {
  loadModelTypeByCategory("modelType");
  loadDataList();
})

async function loadModelTypeByCategory(category) {
  try {
    const response = await axios.get('/api/dictionary/' + category);
    if (response.data.code === 0) {
      const newTypes = Object.entries(response.data.data).map(([key, value]) => ({ key, value }));
      modelTypes.value = [{ key: 'all', value: 'ALL' }, ...newTypes];
    } else {
      console.error('Failed to fetch category:', response.data.error);
    }
  } catch (error) {
    console.error('Error fetching category:', error);
  }
}

async function loadDataList() {
  try {
    var data = {
      pageIndex: currentPage.value,
      pageSize: pageSize.value,
      classType: selectedModelType.value === 'all' ? null : selectedModelType.value
    };

    var ret = await axios.get('/api/alarm', {
      params: data
    });

    if (ret.data.code === 0) {
      dataList.value.length = 0;
      totalCount.value = ret.data.data.total;

      // 转换 base64 字符串为图片 URL 格式
      const alarms = ret.data.data.alarms.map(alarm => ({
        ...alarm,
        // thumbnail: `data:image/png;base64,${alarm.target}`
      }));

      alarms.forEach((v) => {
        dataList.value.push(v);
      });

    } else {
      console.error('Failed to fetch data:', ret.data.error);
      // 可以根据实际情况处理错误，比如弹出错误提示或者执行其他操作
    }
  } catch (error) {
    console.error('Error fetching data:', error);
    // 捕获网络请求失败或其他异常情况，并进行处理
  }
}


// 处理搜索类型变更
async function handleTypeChange() {
  currentPage.value = 1;  // 重置当前页为第一页
  await loadDataList();   // 重新加载数据
}

// json数据读取
function formatBox(box) {
  const width = box.right - box.left;
  const height = box.bottom - box.top;
  return `width: ${width}, height: ${height}`;
}

// 图片点击放大
const openImageInNewTab = (url) => {
  const isBase64 = url.startsWith('data:image');
  let windowUrl = url;

  if (isBase64) {
    const byteString = atob(url.split(',')[1]);
    const mimeString = url.split(',')[0].split(':')[1].split(';')[0];
    const arrayBuffer = new ArrayBuffer(byteString.length);
    const intArray = new Uint8Array(arrayBuffer);
    for (let i = 0; i < byteString.length; i++) {
      intArray[i] = byteString.charCodeAt(i);
    }
    const blob = new Blob([arrayBuffer], { type: mimeString });
    windowUrl = URL.createObjectURL(blob);
  }

  const newWindow = window.open("", "_blank");
  newWindow.document.write(`
    <html>
      <head>
        <title>图片预览</title>
      </head>
      <body style="margin:0; display:flex; justify-content:center; align-items:center; height:100vh;">
        <img src="${url}" style="width:800px; height:600px;">
      </body>
    </html>
  `);
};

function formatTimestamp(timestamp) {
  return moment.utc(timestamp).format('YYYY-MM-DD HH:mm:ss.SSS');
}

async function handleDelete(index, row) {
  try {
    const response = await axios.delete(`/api/alarm/${row.id}`);
    if (response.data.success) {
      // 从 dataList 中移除被删除的数据
      dataList.value.splice(index, 1);

      // 更新 totalCount
      totalCount.value--;

      // 判断是否需要重新加载当前页数据
      if (dataList.value.length < pageSize.value && currentPage.value * pageSize.value <= totalCount.value) {
        await loadDataList();
      }
    } else {
      console.error('Failed to delete alarm:', response.data.error);
    }
  } catch (error) {
    console.error('Error deleting alarm:', error);
  }
}


// change page operation
function handleCurrentChange(row) {
  currentPage.value = row;
  loadDataList();
}
</script>

<template>
  <el-row>
    <el-col :span="6" style="margin: 5px;">
      <el-select v-model="selectedModelType" placeholder="请选择搜索类型" @change="handleTypeChange">
        <el-option v-for="type in modelTypes" :key="type.key" :label="type.value" :value="type.key"></el-option>
      </el-select>
    </el-col>
  </el-row>

  <el-table class="tableClass" :data="dataList" style="width: 100%;" :default-expand-all="true" border
            :header-cell-style="{ background: '#eef1f6', color: '#606266' }" :row-style="{ height: '25px' }"
  >
    <el-table-column type="index" width="45" :align="'center'"></el-table-column>
    <el-table-column prop="id" label="ID" :show-overflow-tooltip="true" :align="'center'"> </el-table-column>
    <el-table-column prop="classType"  label="类型" :align="'center'" :min-width="30" :max-width="40" width="auto">
    </el-table-column>
    <el-table-column prop="box" label="目标大小" :show-overflow-tooltip="true" :align="'center'">
      <template #default="scope">
        <!-- 使用 JSON.stringify 将 JSON 对象转换为字符串 -->
        <pre>{{ formatBox(scope.row.box) }}</pre>
      </template>
    </el-table-column>
    <el-table-column prop="confidence" label="置信度" :align="'center'" :min-width="40" :max-width="50" width="auto">
      <template #default="{ row }">
        {{ row.confidence.toFixed(5) }}
      </template>
    </el-table-column>
    <el-table-column prop="file_path" label="预测图" :align="'center'" :min-width="50" :max-width="60" width="auto">
      <template #default="scope">
        <el-image
            :src="scope.row.file_path+'?w=200&h=140'"
            style="width: 80px; height: 55px; cursor: pointer;"
            @click="openImageInNewTab(scope.row.file_path)"
        ></el-image>
      </template>
    </el-table-column>
<!--    <el-table-column prop="target" label="目标图" :align="'center'"  :min-width="50" :max-width="60" width="auto">-->
<!--      <template #default="scope">-->
<!--        <el-image-->
<!--            v-if="scope.row.thumbnail"-->
<!--            :src="scope.row.thumbnail"-->
<!--            style="width: 80px; height: 55px; cursor: pointer;"-->
<!--            @click="openImageInNewTab(scope.row.thumbnail)"-->
<!--        ></el-image>-->
<!--      </template>-->
<!--    </el-table-column>-->
    <el-table-column prop="timestamp" label="时间" :show-overflow-tooltip="true" :align="'center'" :min-width="58" :max-width="60" width="auto">
      <template #default="scope">
        <span style="font-size: 10px;">
          {{ formatTimestamp(scope.row.timestamp) }}
        </span>
      </template>
    </el-table-column>

    <el-table-column label="操作" width="130" :align="'center'">
      <template #default="scope">
        <el-popconfirm width="220" confirm-button-text="确定" @confirm="handleDelete(scope.$index, scope.row)"
                       cancel-button-text="取消" icon-color="#626AEF" title="确定删除此数据?">
          <template #reference>
            <el-button size="small" type="danger">
              <el-icon>
                <Delete />
              </el-icon>
            </el-button>
          </template>
        </el-popconfirm>

      </template>
    </el-table-column>
  </el-table>

  <el-pagination :page-size="pageSize" :current-page="currentPage" layout="->, total, prev,pager, next" :total="totalCount" @current-change="handleCurrentChange">
  </el-pagination>

</template>



<style scoped></style>





